<?php

// status.php
// Michael Baker
// 2010.06.21
//
// Frontend for status monitor

session_start();
define("IN_MDM", true);

require_once( "includes/all.php" );

$wf = $_GET["wf"];
$tf = $_GET["tf"];

$timeframe_data = ui_get_timeframe_select();
$workflow_data  = $dbase->list_workflows();

$tf_lookup = $timeframe_data[ 0 ];
$tf_lookup_ui = $timeframe_data[ 1 ];

$header_info = "";
if ( $wf && $tf ) {
  if ( array_key_exists( $tf, $tf_lookup ) ) {
    $seconds = $tf_lookup[ $tf ];
    $header_info = "<meta http-equiv=\"refresh\" content=\"$seconds\" />";
  }
}
 
top( "Status", $header_info );

echo get_subheader( "Monitor" );

?>
<span class="textgen">Welcome to the perfSONAR status monitor.</span>
<form action="status.php" method="get">
<table class="input">
<tr>
<td class="label"><span class="textblack">Workflow</span></td>
<td>
<select name="wf">
<?php

$wf_cond = ( $wf && array_key_exists( $wf, $workflow_data ) );

if ( $wf_cond ) {
  $t = $workflow_data[ $wf ];
  echo "<option value=\"$wf\">$t</option>";
}

foreach ( array_keys($workflow_data) as $id ) {
  $t  = $workflow_data[ $id ];
  
  if ( $wf_cond && ( $id == $wf ) ) {
    // skip current workflow, because we already outputted it
    continue;
  }
  
  echo "<option value=\"$id\">$t</option>";
}

?>
</select>
</td>
<td class="label"><span class="textblack">Timeframe</span></td>
<td>
<select name="tf">
<?php

$tf_cond = ( $tf && array_key_exists( $tf, $tf_lookup ) );

if ( $tf_cond ) {
  // if they have chosen a timeframe already, output it at the top of the dropdown
  
  $t = $tf_lookup_ui[ $tf ];
  echo "<option value=\"$tf\">$t</option>";
}


foreach ( array_keys($tf_lookup_ui) as $id ) {
  $t  = $tf_lookup_ui[ $id ];

  if ( $tf_cond && ( $id == $tf ) ) {
    // skip the current timeframe, because we already outputted it
    continue;
  }
    
  echo "<option value=\"$id\">$t</option>";
}

?>
</select>
</td>

<td>
<input type="submit" value="View" />
</td>
</tr>

</table>
</form>
<?php

if ( $wf && $tf ) {
  // Try to process it
  
  try {
    $workflow = $dbase->get_workflow( $wf );
  }
  catch (DatabaseException $e) {
    $err = "Failed to retrieve workflow $wf";
    output_error( $err ); bot();
  }
  
  $tf_lookup = $timeframe_data[ 0 ];
  
  if ( !array_key_exists( $tf, $tf_lookup ) )
    throw new Exception( "Invalid timeframe code: $tf" );
  
  $seconds = $tf_lookup[ $tf ];
  $timeThen = microtime( true );
  try {
    $workflow->process( array( time() - $seconds, time() ) );  
  }
  catch (Exception $e) {
    output_error( $e->getMessage() ); bot();
  }
  
  $timeNow = microtime( true );
  $p_time  = number_format( ($timeNow - $timeThen)*1000, 2 );
  $_SESSION["wf"] = serialize( $workflow );
  
  echo "<img src=\"mk_status_img.php\" alt=\"(status diagram)\" /><br /><br />";
  echo "<span class=\"textsm\">Processed in $p_time ms (" . number_format($dbtime*1000,2) . " ms DBQ; " . number_format($dbtime2*1000,2) . " ms DBC)</span>";  
}

bot();

?>